package com.pn.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.pn.entity.InStore;
import com.pn.entity.Purchase;
import com.pn.mapper.PurchaseMapper;
import com.pn.service.PurchaseService;
import com.pn.utils.PageBean;
import com.pn.utils.Result;
import com.pn.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Map;

@Service
public class PurchaseServiceImpl implements PurchaseService {

    @Autowired
    private PurchaseMapper purchaseMapper;

    //添加采购单
    @Override
    public Result insertPurchase(Purchase purchase) {
        purchase.setFactBuyNum(purchase.getBuyNum());
        int i = purchaseMapper.insertPurchase(purchase);
        if (i >0){
            return Result.ok("添加采购单成功");
        }
        return Result.err(Result.CODE_ERR_BUSINESS,"添加采购单失败");
    }

    //显示采购列表
    @Override
    public PageBean purchasePageList(Purchase purchase) {
        PageHelper.startPage(purchase.getPageNum(),purchase.getPageSize());
        Page<Purchase> page = purchaseMapper.purchasePageList(purchase);
        return new PageBean(page.getTotal(),page.getResult());
    }

    //删除采购单
    @Override
    public Result purchaseDeleteByid(Integer buyId) {
        int i = purchaseMapper.purchaseRemoveByid(buyId);
        if (i > 0 ){
            return Result.ok("删除采购单成功!");
        }
        return Result.err(Result.CODE_ERR_BUSINESS,"删除采购单失败！");
    }

    //修改采购单
    @Override
    public Result purchaseUpdate(Purchase purchase) {
        int i = purchaseMapper.purchaseUpdateByid(purchase);
        if (i > 0 ){
            return Result.ok("修改采购单成功!");
        }
        return Result.err(Result.CODE_ERR_BUSINESS,"修改采购单失败！");
    }

    //采购单生成入库单
    @Transactional
    @Override
    public Result inWarehouseRecordAdd(Purchase purchase) {
        //根据buyId修改is_id为1
        purchaseMapper.updateIsInByid(purchase.getBuyId());
        Map<String,Object> map =(Map<String, Object>) ThreadLocalUtil.get();
        Integer userId =(Integer) map.get("userId");
        InStore inStore = new InStore();
        inStore.setStoreId(purchase.getStoreId());
        inStore.setCreateBy(userId);
        inStore.setProductId(purchase.getProductId());
        inStore.setInNum(purchase.getFactBuyNum());
        inStore.setIsIn(0);
        //生成入库单
        int i = purchaseMapper.insertInStore(inStore);
        if (i > 0 ){
            return Result.ok("添加入库单成功!");
        }
        return Result.err(Result.CODE_ERR_BUSINESS,"添加入库单失败！");

    }
}
